from nicegui import ui
import plotly.graph_objects as go

# 初始化数据点（包含 x, y, z 坐标）
points = []

# 创建三维 Plotly 图表
fig = go.Figure()

# 初始化三维散点图
fig.add_trace(go.Scatter3d(
    x=[], y=[], z=[],
    mode='markers',
    marker=dict(size=5),
    name='Points'
))

# 更新图表函数
def update_plot():
    fig.data[0].x = [p[0] for p in points]
    fig.data[0].y = [p[1] for p in points]
    fig.data[0].z = [p[2] for p in points]
    plot.update()  # 强制更新图表显示

# 添加点函数
def add_point():
    try:
        x = float(x_input.value)
        y = float(y_input.value)
        z = float(z_input.value)
        point = (x, y, z)
        if point in points:
            ui.notify("该点已存在！", type='warning')
        else:
            points.append(point)
            update_plot()
        x_input.value = y_input.value = z_input.value = ''  # 清空输入框
    except ValueError:
        ui.notify("请输入有效的数字！", type='negative')

# 删除指定点函数
def remove_point():
    try:
        x = float(x_input.value)
        y = float(y_input.value)
        z = float(z_input.value)
        point = (x, y, z)
        if point in points:
            points.remove(point)
            update_plot()
            ui.notify(f"已删除点 {point}", type='positive')
        else:
            ui.notify("该点不存在，无法删除！", type='warning')
        x_input.value = y_input.value = z_input.value = ''  # 清空输入框
    except ValueError:
        ui.notify("请输入有效的数字！", type='negative')

# 创建界面
with ui.column():
    plot = ui.plotly(fig).classes('w-full h-96')
    with ui.row():
        x_input = ui.input(label='X 坐标', placeholder='例如：1.0')
        y_input = ui.input(label='Y 坐标', placeholder='例如：2.0')
        z_input = ui.input(label='Z 坐标', placeholder='例如：3.0')
    with ui.row():
        ui.button('添加三维点', on_click=add_point).classes('bg-green-200')
        ui.button('删除指定点', on_click=remove_point).classes('bg-red-200')

# 设置三维坐标系显示范围（可选）
fig.update_layout(
    scene=dict(
        xaxis=dict(range=[-10, 10]),
        yaxis=dict(range=[-10, 10]),
        zaxis=dict(range=[-10, 10])
    )
)

ui.run()
